package io.gitee.zhangbinhub.admin.oauth.init

import io.gitee.zhangbinhub.acp.boot.init.AcpInitialization
import io.gitee.zhangbinhub.acp.boot.log.LogAdapter
import io.gitee.zhangbinhub.admin.common.constant.RoleCode
import io.gitee.zhangbinhub.admin.oauth.conf.AcpOauthServerAutoConfiguration
import io.gitee.zhangbinhub.admin.oauth.service.ApplicationService
import io.gitee.zhangbinhub.admin.oauth.service.InitDataService
import io.gitee.zhangbinhub.admin.oauth.service.RoleService
import io.gitee.zhangbinhub.admin.oauth.service.UserService
import org.springframework.stereotype.Component

@Component
class DataInitialization(
    private val logAdapter: LogAdapter,
    private val applicationService: ApplicationService,
    private val userService: UserService,
    private val roleService: RoleService,
    private val initDataService: InitDataService,
    private val acpOauthServerAutoConfiguration: AcpOauthServerAutoConfiguration
) : AcpInitialization {
    override val name: String
        get() = "Data Initialization"

    override val order: Int
        get() = 1

    override fun doInit() {
        applicationService.getAppList().apply {
            if (this.isEmpty()) {
                logAdapter.info(">>>>>>>>>>>>>>>>>>>> begin init system resource data...")
                initDataService.doInitResources()
                logAdapter.info(">>>>>>>>>>>>>>>>>>>> init system resource data has finished!")
            }
            acpOauthServerAutoConfiguration.loadClientInfo()
        }
        userService.getUserVoListByRole(listOf(RoleCode.SUPER)).apply {
            if (this.isEmpty()) {
                logAdapter.info("admin user is not existed")
                logAdapter.info("begin init admin user...")
                roleService.getRoleList().filter { role -> role.code == RoleCode.SUPER }.let { roleList ->
                    initDataService.initAdminUser(roleList)
                }
                logAdapter.info("init admin user has finished!")
            }
        }
    }
}